package com.ly.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ly.cloud.api.ISysBaseAPI;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.MsgDTO;
import com.ly.system.mapper.SysPermissionMapper;
import com.ly.system.mapper.SysUserRoleMapper;
import com.ly.system.service.ISysCommonService;
import com.ly.system.service.ISysDictService;
import com.ly.system.system.bean.entity.SysPermission;
import com.ly.system.system.bean.entity.SysUserRole;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 底层共通业务API，提供其他独立模块调用
 *
 * @author jeecg
 * @Date:2019-4-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysBaseApiImpl implements ISysBaseAPI {

    private final SysUserRoleMapper sysUserRoleMapper;
    private final ISysDictService sysDictService;
    private final SysPermissionMapper sysPermissionMapper;
    private final ISysCommonService sysCommonService;

    /**
     * 发消息
     */
    @Override
    public void sendMsg(MsgDTO dto) {
        sysCommonService.sendMsg(dto);
    }

    @Override
    public Set<String> getUserRoleSetById(String useId) {
        // 查询用户拥有的角色集合
        List<SysUserRole> list = sysUserRoleMapper.selectList(
                new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, useId)
        );
        List<String> roles = list.stream().map(n -> n.getRoleId()).collect(Collectors.toList());
        log.info("-------通过数据库读取用户拥有的角色Rules------useId： " + useId + ",Roles size: " + (roles == null ? 0 : roles.size()));
        return new HashSet<>(roles);
    }

    @Override
    public Set<String> getUserPermissionSet(String userId) {
        List<SysPermission> permissionList = sysPermissionMapper.getAuthByUserId(userId);
        Set<String> permissionSet = permissionList.stream().map(n -> n.getPerms()).collect(Collectors.toSet());
        log.info("-------通过数据库读取用户拥有的权限Perms------userId： " + userId + ",Perms size: " + (permissionSet == null ? 0 : permissionSet.size()));
        return permissionSet;
    }

    @Override
    public R getTenantById(String id) {
        return null;
    }
    // @Override
    // public DynamicDataSourceModel getDynamicDbSourceByCode(String dbSourceCode) {
    //     SysDataSource dbSource = dataSourceService.getOne(new LambdaQueryWrapper<SysDataSource>().eq(SysDataSource::getCode, dbSourceCode));
    //     if (dbSource != null && StrUtil.isNotBlank(dbSource.getDbPassword())) {
    //         String dbPassword = dbSource.getDbPassword();
    //         String decodedStr = SecurityUtil.jiemi(dbPassword);
    //         dbSource.setDbPassword(decodedStr);
    //     }
    //     return new DynamicDataSourceModel(dbSource);
    // }
}